import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

import { MOCK_USER_ID, MOCK_USER_TOKEN } from "@/config/env.js";

import plugins_request from "@/plugin/request.js";
let api = plugins_request.api;

const store = new Vuex.Store({
  state: {
    vuex_avatar_default: require("@/static/common/avatar.png"),
    vuex_user: {},
    userInfo: {}, //用户信息
    //
    vuex_config: {},
    //
    vuex_is_login: false,

    //
    //商城部分
    vuex_cart_number: 0,
    vuex_huobi: "￥",
    //

    //定位相关
    //默认定位地点 - 使用 getLocation 定位接口获取的地理位置
    vuex_default_location: {
      location_title: "",
      location_longitude: "",
      location_latitude: "",
    },
    //选择的地点 - 当前位置不准确时  用户手动选择的地理位置 例如通过 chooseLocation  choosePoi 接口选择
    vuex_select_location: {
      location_title: "",
      location_longitude: "",
      location_latitude: "",
    },
    //定位相关
  },
  mutations: {
    set_vuex_data(state, obj) {
      let key = obj.key;
      let val = obj.val;
      state[key] = val;
    },
    set_vuex_config(state, data) {
      state.vuex_config = data;
    },

    //设置基本信息
    set_vuex_user(state, data) {
      console.log("vuex set_vuex_user 用户信息", {
        ...data,
      });

      // debugger
      let { token, userId, id } = data;

      // if (!!id && !userId) {
      // 	userId = id
      // }
      // if (!token) {
      // 	token = uni.getStorageSync('token');
      // 	userId = uni.getStorageSync('userId');
      // }

      //测试用
      state.vuex_is_login = true;
      //当前调试时，需要打开
      if (!data.mobile || !data.image) {
        state.vuex_is_login = false;
      }
      state.userInfo = data;
      state.vuex_user = data;

      uni.setStorageSync("token", token);
      uni.setStorageSync("userId", userId || id);
      uni.setStorageSync("vuex_user", data);
      uni.setStorageSync("userInfo", data);
    },
    //修改用户信息
    edit_vuex_user(state, data = {}) {
      let info = {
        ...state.userInfo,
        ...data,
      };
      state.userInfo = info;
      state.vuex_user = info;
      uni.setStorageSync("vuex_user", info);
      uni.setStorageSync("userInfo", info);
    },
    //设置基本信息
    remove_vuex_user(state) {
      state.userInfo = {};
      state.vuex_user = {};
      state.vuex_is_login = false;

      uni.removeStorageSync("token");
      uni.removeStorageSync("userId");
      uni.removeStorageSync("vuex_user");
      uni.removeStorageSync("userInfo");
    },

    //保存邀请人id
    cache_invite_id(state, data) {
      console.warn("vuex 邀请人id=", data);
      uni.setStorageSync("cache_invite_id", data);
    },

    /**
     * @param {Object} state
     * @param {Object} data
     * H5 环境测试使用  固定用户token
     */
    set_test_user_in_web(state, data) {
      uni.setStorageSync("userId", MOCK_USER_ID);
      uni.setStorageSync("token", MOCK_USER_TOKEN);
    },

    //缓存用户经纬度信息 - 定位获取
    set_vuex_default_location(state, data) {
      console.log("更新vuex 默认 地理位置", data);
      let value = {
        location_title: data.location_title || "锡林郭勒",
        longitude: data.longitude,
        latitude: data.latitude,
      };

      uni.setStorageSync("cache_default_location", value);
      state.vuex_default_location = value;
    },

    //缓存用户经纬度信息 - 用户手动选点获取
    set_vuex_select_location(state, data) {
      console.log("更新vuex 选择 地理位置", data);
      let value = {
        location_title: data.location_title || "铜陵",
        longitude: data.longitude,
        latitude: data.latitude,
      };

      uni.setStorageSync("cache_select_location", value);
      state.vuex_select_location = value;
    },

    //待支付商品信息 产品详情 购物车设置存储
    set_cache_payment_products(state, str_products) {
      console.log("vuex 缓存商品信息", str_products);
      uni.setStorageSync("cache_payment_products", str_products);
    },

    //待兑换的积分商品信息 - 【积分兑换-兑换下单】使用
    set_cache_payment_points_products(state, data) {
      console.log("缓存兑换商品信息", data);
      uni.setStorageSync("cache_payment_points_products", data);
    },

    //购物车去下单
    set_vuex_cart_number(state, value) {
      console.log("更新vuex 购物车商品数量", value);
      state.vuex_cart_number = value;

      if (value > 0) {
        uni.setTabBarBadge({
          index: 2,
          text: `${value}`,
        });
      } else {
        uni.removeTabBarBadge({
          index: 2,
        });
      }
    },

    set_cache_tabbar_query(state, data) {
      console.log("缓存分类初始化数据", data);
      uni.setStorageSync("cache_tabbar_query", data);
    },

    //结算时默认的地址信息
    set_cache_payment_address_id(state, data) {
      uni.setStorageSync("cache_payment_address_id", data);
    },
    //售后-换货-收货地址
    set_cache_refund_address_id(state, data) {
      uni.setStorageSync("cache_refund_address_id", data);
    },

    //商品搜索历史 - 【产品搜索页面】使用
    set_cache_product_search_keywords(state, data) {
      console.log("缓存商品搜索历史", data);

      let { type, value } = data;
      if (type == "新增") {
        let _cache = uni.getStorageSync("cache_product_search_keywords");
        let list = null;
        if (_cache) {
          console.log("搜索历史", _cache);
          list = _cache;
          let index = list.findIndex((v) => v == value);
          if (index > -1) {
            list.splice(index, 1);
          }
        } else {
          list = [];
        }
        list.unshift(value);
        uni.setStorageSync("cache_product_search_keywords", list);
      } else if (type == "清空") {
        uni.clearStorageSync("cache_product_search_keywords");
      }
    },
  },
  actions: {
    //获取已开通的城市
    async getConfig({ commit, state, dispatch }) {
      api({
        url: "/setting",
        method: "get",
        data: {
          // action: "index_config",
        },
      }).then((res) => {
        if (res.code == 200) {
          commit("set_vuex_config", res.data);
        }
      });
      // api({
      // 	url: '/service.php',
      // 	method: 'post',
      // 	data: {
      // 		action: 'index_index',
      // 		position: 3,
      // 	},
      // }).then(res => {
      // 	if (res.code == 200) {

      // 	}
      // })
    },

    // 获取用户信息
    // this.$store.dispatch('query_user')
    async query_user({ commit, state, dispatch }, params) {
      api({
        url: "/getUserInfo",
        method: "get",
        data: {
          // action: "users_userInfo",
          ...params,
        },
      }).then((res) => {
        console.log("vuex 获取用户信息", res);
        if (res.code == 200) {
          commit("set_vuex_user", res.data);
        } else {
          commit("remove_vuex_user", false);
        }
      });
    },

    // 保存用户位置信息
    async saveUserLocation({ commit, state, dispatch }, params) {
      api({
        url: "/service.php",
        method: "get",
        data: {
          longitude: params.longitude,
          latitude: params.latitude,
        },
      }).then((res) => {
        this.$logjson("vuex 保存用户位置信息", res);
        if (res.code == 200) {
          commit("edit_vuex_user", {
            ...params,
          });
        }
      });
    },
    // 导出
    async exportInfo({ commit, state, dispatch }, params) {
      uni.showLoading({
        title: "下载中",
      });
      api({
        url: "/export",
        method: "get",
        data: params,
      }).then((res) => {
        uni.downloadFile({
          url: res.data.url, //仅为示例，并非真实的资源
          success: (res) => {
            if (res.statusCode === 200) {
              console.log("下载成功");
              uni.openDocument({
                filePath: res.tempFilePath,
                showMenu: true,
                success: function (ret) {
                  uni.hideLoading();
                  console.log("openDocument 打开文档成功 res", ret);
                },
                fail: function (ret) {
                  uni.hideLoading();
                },
              });
            }
          },
        });
        console.log(res);
      });
    },
  },
});

export default store;
